package com.drm.netschool.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.drm.common.util.ConfigUtil;
import com.drm.common.util.CookieUtil;
import com.drm.common.util.JsonMapper;
import com.drm.common.util.NumberUtil;
import com.drm.common.util.StringUtil;
import com.drm.common.util.constants.Constants;
import com.drm.netschool.entity.CourseCategoryBean;
import com.drm.netschool.entity.DrmArticles;
import com.drm.netschool.entity.DrmCourse;
import com.drm.netschool.entity.DrmCourseComment;
import com.drm.netschool.entity.DrmCourseOffline;
import com.drm.netschool.entity.DrmCourseStatus;
import com.drm.netschool.entity.DrmCourseType;
import com.drm.netschool.entity.DrmCoursefaceApply;
import com.drm.netschool.entity.DrmUser;
import com.drm.netschool.entity.extend.RecommendCourse;
import com.drm.netschool.entity.extend.UserInfo;
import com.drm.netschool.mongo.MongoDao;
import com.drm.netschool.service.DrmArticlesService;
import com.drm.netschool.service.DrmCourseCommentService;
import com.drm.netschool.service.DrmCourseCountService;
import com.drm.netschool.service.DrmCourseService;
import com.drm.netschool.service.DrmCourseTypeService;
import com.drm.netschool.service.DrmCoursefaceApplyService;
import com.drm.netschool.service.DrmSystemSettingService;
import com.drm.netschool.service.DrmUserCacheService;
import com.drm.netschool.service.DrmUserService;
import com.drm.netschool.service.OrderService;
import com.drm.netschool.web.annotation.AccessRequired;
import com.drm.netschool.web.form.CourseForm;

@Controller
@RequestMapping("/course/")
public class CourseController {
	
	private Logger LOGGER = LoggerFactory.getLogger(CourseController.class);
	
	@Autowired
	private DrmCourseService courseService;
	
	@Autowired
	private DrmUserService userService;
	
	@Autowired
	private DrmUserCacheService userCacheService;
	
	@Autowired
	private DrmCourseCountService courseCountService;
	
	@Autowired
	private DrmCourseTypeService drmCourseTypeService;
	
	@Autowired
	private DrmCourseCommentService courseCommentService;
	
	@Autowired
	private DrmArticlesService articlesService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	@Qualifier("mongoDao")
	private MongoDao mongoDao;
	
	@Autowired
	private DrmSystemSettingService systemSettingService;
	
	@Autowired
	private DrmCoursefaceApplyService coursefaceApplyService;
	
	@RequestMapping(value = "{type}", method = RequestMethod.GET)
	@ResponseBody
	public List<DrmCourse> getCourseList(@PathVariable String type){
		LOGGER.info("getCourseList  type:" + type);
		DrmCourse course = new DrmCourse();
		course.setCourseTp(1L);
		return courseService.getListByPage(course, 1, 5);
	}
	
	@RequestMapping(value = "recommend-course", method = RequestMethod.GET)
	@ResponseBody
	public List<RecommendCourse> getRecommendCourses(HttpServletRequest request, HttpServletResponse response){
		return courseService.getRecommendCourses(new RecommendCourse(), 1, 3);
	}
	
	@RequestMapping(value = "list")
	public String list(@ModelAttribute("form") CourseForm form, HttpServletRequest request, HttpServletResponse response){
		form.setMetaInfo(systemSettingService.getDrmSystemSetting());
		
		//根据课程分类&排序获取课程列表信息
		form.setCourseTypeList(drmCourseTypeService.getListByPage(new DrmCourseType(), 1, null));
		form.setPageSize(16);
		
		RecommendCourse entity = new RecommendCourse();
		if(form.getSort() == 1){
			entity.setCourseTp(NumberUtil.parseLong(form.getType()));
			entity.setOrderBy("courseCdt");
		}else if(form.getSort() == 2){
			entity.setCourseTp(NumberUtil.parseLong(form.getType()));
			entity.setOrderBy("courseBoutique");
		}else if(form.getSort() == 3){
			entity.setCourseTp(NumberUtil.parseLong(form.getType()));
			entity.setOrderBy("courseBrowsercnt");
		}else if(form.getSort() == 4){
			entity.setCourseTp(NumberUtil.parseLong(form.getType()));
			entity.setCourseSubject(2);
		}else if(form.getSort() == 5){
			entity.setCourseOnlinetp(2);
		}else if(form.getSort() == 6){
			entity.setCourseClass("1");
		}
		entity.setKeyword(StringUtil.empty(form.getKeyword()) ? null : form.getKeyword().trim());
		int total = courseService.getRecommendCoursesCount(entity);
		form.setTotalRecords(total);
		if(total > 0){
			List<RecommendCourse> list = courseService.getRecommendCourses(entity, form.getPage(), form.getPageSize());
			if(list != null && list.size() > 0){
				for(RecommendCourse c : list){
					DrmCourseComment comment = courseCommentService.getByCourseId(c.getCourseId());
					c.setCommentStar(comment == null ? 0 : comment.getCommentStar());
				}
			}
			form.setCourseList(list);
		}
		
		//最新动态
		DrmArticles articles = new DrmArticles();
		articles.setArticleTp(203);
		articles.setArticlePublishyn(1);
		form.setArticlesList(articlesService.getListByPage(articles, 1, 5));
		return "course/list";
	}
	
	@RequestMapping(value = "detail/{courseId}")
	public String detail(@PathVariable Long courseId, @ModelAttribute("form") CourseForm form, HttpServletRequest request, HttpServletResponse response){
		LOGGER.info("courseDetail:::" + courseId);
		form.setMetaInfo(systemSettingService.getDrmSystemSetting());
		
		//校验课程审核状态和上下架
		DrmCourseStatus status = courseService.getCourseStatusByCourseId(courseId);
		if(status == null || status.getCourseCheckyn() != 1 || status.getCoursePublishyn() != 1){
			throw new RuntimeException(courseId + ",课程不存在.");
		}
				
		RecommendCourse course = courseService.getCourseDetail(courseId);
		if(course == null){
			return "course/detail";
		}
		
		// for test course.setContent("<div class=\"infor_detailtxt\"> <p>北京中建政研信息咨询中心（以下简称中建政研）依托住房和城乡建设部政策研究中心于2004年经相关部门批准正式成立。目前以形成集行业会议、职业教育、赴企内训、咨询服务、高端研修、国际交流、产品推广、组织论坛等业务为一体的专业服务机构，中心致力于为行业搭建立体性、全方位综合服务平台。</p> <p>“追求卓越、开拓创新”是中建政研人执着的信念。“顶级专家、一流服务”是中建政研不变的承诺，而今，中建政研正迈着务实、稳健、快速的步伐，立足眼前、放眼未来，以专业、领先、专注、创新的精神风貌打造中国管理咨询与培训业的领导品牌，助力企业成长，推动行业发展！</p> <p><b>企业愿景：</b></p> <p>成为中国本土一流的咨询培训中心，专业的会展组织！</p> <p><b>企业使命：</b></p> <p>致力于为行业搭建立体型，全方位综合服务平台！</p> <p><b>企业精神：</b></p> <p>追求卓越，开拓创新！</p> <p><b>企业宗旨：</b></p> <p>稳定和高素质的员工，是企业 发展的基础！</p> <p>优质和持续的业务是企业发展的动力！</p> <p>明确和先进的制度是企业发展的保障！</p> </div>");
		int courseSize = 0;
		if (course.getCourseSubject() != null && course.getCourseSubject() == 2) {
			List<RecommendCourse> cList = courseService.subjectCourselist(courseId);
			form.setcList(cList);
			courseSize = cList == null || cList.isEmpty() ? 0 : cList.size();
		} else {
			List<CourseCategoryBean> courseCategoryList = courseService.courseCatelist(courseId);
			form.setCourseCategoryList(courseCategoryList);
			courseSize = courseCategoryList == null || courseCategoryList.isEmpty() ? 0 : courseCategoryList.size();
		}
		course.setCourseSize(courseSize);
		
		form.setBuyrecord(courseService.getBuyOrders(courseId, form.getPage(), form.getPageSize()));
		
		
		//add 2015年10月1日  17：22
		CookieUtil cookieUtil = new CookieUtil(request, response, ConfigUtil.getString("cookie.domain"));
    	String key = cookieUtil.getCookie(Constants.COOKIE_USER_ID,false);
    	DrmUser loginUser = userCacheService.getUserCache(key);
    	
    	LOGGER.info( "loginUser ==" + JsonMapper.toJson(loginUser) );
    	
    	UserInfo userInfo = userService.getUserInfoList(course.getCourseTeacherid());
		form.setTeacher(userInfo);
		
		//面授课程的老师介绍
		if(course.getCourseOnlinetp()!=null && NumberUtil.parseInteger(course.getCourseOnlinetp()) == 2){
			//面授课程
			DrmCourseOffline offlineInfo = courseService.baseOffCourseById(courseId);
			form.setOfflineInfo(offlineInfo);
			if(userInfo != null && offlineInfo != null){	//讲师介绍
				userInfo.setContend(mongoDao.getContentById(offlineInfo.getCourseTeacherDesc()));
			}
		}
		
		//购买数量  粉丝数量  浏览数量，
		form.setCount(courseCountService.getByCourseId(courseId));
		form.setCourse(course);
		//相关课程
		RecommendCourse entity = new RecommendCourse ();
		entity.setCourseTp(course.getCourseTp());
		form.setCourseList(courseService.getRecommendCourses(new RecommendCourse(), 1, 3));
		//如果没有登陆
		if(loginUser==null){
			form.setBuyFlag( false );
		}else{
			//登陆了查询
			form.setBuyFlag(orderService.getByUserIdAndCourseId(loginUser.getUserId(), courseId) == null ? false : true);
		}
		
		return "course/detail";
	}
	
	@AccessRequired
	@RequestMapping(value = "nowstudy/{courseId}")
	public String studyRightNow(@PathVariable Long courseId, HttpServletRequest request, HttpServletResponse response){
		DrmUser user = null;
		CookieUtil cookieUtil = new CookieUtil(request, response, ConfigUtil.getString("cookie.domain"));
		String key = cookieUtil.getCookie(Constants.COOKIE_USER_ID,false);
		if (!StringUtil.empty(key))
			user = userCacheService.getUserCache(key);

		if (user == null) {
			return "login/login";
		}
		RecommendCourse course = courseService.getCourseDetail(courseId);
		if(course == null || !"1".equals( course.getCourseClass() ) ){
			return "course/detail";
		}
		
		return "redirect:http://student.zhuclass.com/student/curriculum/pinitCourseCtg/"+courseId.toString();
	}
	
	@AccessRequired
	@RequestMapping(value = "signup/{courseId}")
	public Map<String, Object> signUp(@PathVariable Long courseId, @ModelAttribute("form") CourseForm form, HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			DrmUser user = null;
			CookieUtil cookieUtil = new CookieUtil(request, response, ConfigUtil.getString("cookie.domain"));
			String key = cookieUtil.getCookie(Constants.COOKIE_USER_ID,false);
			if (!StringUtil.empty(key))
				user = userCacheService.getUserCache(key);

			if (user == null) {
				result.put("status", "用户未登录!");
				return result;
			}
			
			DrmCoursefaceApply entity = coursefaceApplyService.getByUserIdAndCourseId(user.getUserId(), courseId);
			if(entity == null){
				entity = new DrmCoursefaceApply();
				entity.setCourseId(courseId);
				entity.setUserId(user.getUserId());
				coursefaceApplyService.insert(entity);
			}
			result.put("status", "200");
		} catch (Exception e) {
			LOGGER.error(courseId + ",报名异常!", e);
			result.put("status", "系统异常!");
		}
		return result;
	}
}
